package com.yoshino.usercenter.controller;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.yoshino.usercenter.exception.BusinessException;
import com.yoshino.usercenter.service.UserService;
import com.yoshino.usercenter.utils.EmailUtils;
import com.yoshino.yoshinoapicommon.common.BaseResponse;
import com.yoshino.yoshinoapicommon.common.ErrorCode;
import com.yoshino.yoshinoapicommon.common.ResultUtils;
import com.yoshino.yoshinoapicommon.model.entity.User;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;


/**
 * 邮件管理
 * @author yoshino
 **/
@RestController
@RequestMapping("/email")
@Slf4j
public class EmailController {

    @Autowired
    private EmailUtils emailUtils;

    @Resource
    private UserService userService;

    @GetMapping("/getCode")
    public BaseResponse<String> getCode(@RequestParam String registerEmail) {
        if (registerEmail == null) {
            throw new BusinessException(ErrorCode.NULL_ERROR);
        }
        if (!EmailUtils.isValidEmail(registerEmail)) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR, "邮箱格式有误");
        }
        // 邮箱已被注册
        if (userService.count(new QueryWrapper<User>().eq("email", registerEmail)) > 0) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR, "邮箱已注册");
        }
        emailUtils.sendEmail(registerEmail);
        return ResultUtils.success("验证码已成功发送!");
    }
}
